package com.ruoyi.transfers.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.enums.GoodsTransferStatus;
import com.ruoyi.common.enums.RuleType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.order.OrderUtils;
import com.ruoyi.fee.domain.WGoodsTransferFeeRule;
import com.ruoyi.fee.service.IWGoodsTransferFeeRuleService;
import com.ruoyi.goods.domain.TGoodsInfo;
import com.ruoyi.goods.domain.TGoodsWeightSum;
import com.ruoyi.goods.service.ITGoodsInfoService;
import com.ruoyi.transfers.domain.TimeLineActivity;
import com.ruoyi.transfers.domain.WGoodsTransferAccount;
import com.ruoyi.transfers.service.IWGoodsTransferAccountService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.transfers.domain.WGoodsTransferInfo;
import com.ruoyi.transfers.service.IWGoodsTransferInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 货转信息Controller
 * 
 * @author wzy
 * @date 2024-09-09 13:25:55
 */
@RestController
@RequestMapping("/transfers/transfer")
public class WGoodsTransferInfoController extends BaseController
{
    @Autowired
    private IWGoodsTransferInfoService wGoodsTransferInfoService;

    @Autowired
    private ITGoodsInfoService tGoodsInfoService;

    @Autowired
    private IWGoodsTransferFeeRuleService wGoodsTransferFeeRuleService;

    @Autowired
    private IWGoodsTransferAccountService wGoodsTransferAccountService;

    private static Logger logger = LoggerFactory.getLogger(WGoodsTransferInfoController.class);
    /**
     * 查询货转信息列表
     */
    @PreAuthorize("@ss.hasPermi('transfers:transfer:list')")
    @GetMapping("/list")
    public TableDataInfo list(WGoodsTransferInfo wGoodsTransferInfo)
    {
        startPage();
        List<WGoodsTransferInfo> list = wGoodsTransferInfoService.selectWGoodsTransferInfoList(wGoodsTransferInfo);
        return getDataTable(list);
    }

    /**
     * 导出货转信息列表
     */
    @PreAuthorize("@ss.hasPermi('transfers:transfer:export')")
    @Log(title = "货转信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WGoodsTransferInfo wGoodsTransferInfo)
    {
        List<WGoodsTransferInfo> list = wGoodsTransferInfoService.selectWGoodsTransferInfoList(wGoodsTransferInfo);
        ExcelUtil<WGoodsTransferInfo> util = new ExcelUtil<WGoodsTransferInfo>(WGoodsTransferInfo.class);
        util.exportExcel(response, list, "货转信息数据");
    }

    /**
     * 获取货转信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('transfers:transfer:query')")
    @GetMapping(value = "/{goodsTransferId}")
    public AjaxResult getInfo(@PathVariable("goodsTransferId") Long goodsTransferId)
    {
        return success(wGoodsTransferInfoService.selectWGoodsTransferInfoByGoodsTransferId(goodsTransferId));
    }

    /**
     * 新增货转信息
     */
    @PreAuthorize("@ss.hasPermi('transfers:transfer:add')")
    @Log(title = "货转信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WGoodsTransferInfo wGoodsTransferInfo)
    {
        wGoodsTransferInfo.setGoodsTransferNumber(OrderUtils.getOrderNumber("TO", "-"));
        wGoodsTransferInfo.setGoodsTransferStatus(GoodsTransferStatus.NOT.getCode());
        wGoodsTransferInfo.setCreateBy(getNickName());
        return toAjax(wGoodsTransferInfoService.insertWGoodsTransferInfo(wGoodsTransferInfo));
    }

    /**
     * 修改货转信息
     */
    @PreAuthorize("@ss.hasPermi('transfers:transfer:edit')")
    @Log(title = "货转信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WGoodsTransferInfo wGoodsTransferInfo)
    {
        // 先判断当前作业在数据库中的状态，防止2人重复操作)
        WGoodsTransferInfo goodsTransferInfo = wGoodsTransferInfoService.selectWGoodsTransferInfoByGoodsTransferId(wGoodsTransferInfo.getGoodsTransferId());
        if(StringUtils.isNull(goodsTransferInfo)) {
            return error("当前作业，已删除，作业修改失败！");
        } else if(goodsTransferInfo.getGoodsTransferStatus().equals("1")) {
            return error("当前作业，已过审，作业修改失败！");
        }

        wGoodsTransferInfo.setUpdateBy(getNickName());
        return toAjax(wGoodsTransferInfoService.updateWGoodsTransferInfo(wGoodsTransferInfo));
    }

    /**
     * 删除货转信息
     */
    @PreAuthorize("@ss.hasPermi('transfers:transfer:remove')")
    @Log(title = "货转信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{goodsTransferIds}")
    public AjaxResult remove(@PathVariable Long[] goodsTransferIds)
    {
        // 先判断当前作业在数据库中的状态，防止2人重复操作)
        for(Long goodsTransferId : goodsTransferIds) {
            WGoodsTransferInfo goodsTransferInfo = wGoodsTransferInfoService.selectWGoodsTransferInfoByGoodsTransferId(goodsTransferId);
            if (StringUtils.isNotNull(goodsTransferInfo) && goodsTransferInfo.getGoodsTransferStatus().equals("1")) {
                return error("当前作业，已过审，作业删除失败！");
            }
        }
        //货物状态，需要改成“已在库”
        tGoodsInfoService.updateTGoodsInventoryStatusByTransferIds(goodsTransferIds, "已在库");
        return toAjax(wGoodsTransferInfoService.deleteWGoodsTransferInfoByGoodsTransferIds(goodsTransferIds));
    }

    /**
     * 修改货转信息
     */
    @PreAuthorize("@ss.hasPermi('transfers:transfer:audit')")
    @Log(title = "货转信息", businessType = BusinessType.AUDIT)
    @PutMapping("/audit")
    public AjaxResult audit(@RequestBody WGoodsTransferInfo wGoodsTransferInfo)
    {
        //logger.debug("CCC " + "audit = " + wGoodsTransferInfo);
        Integer rtn = 0;
        String transferOrderNumber = wGoodsTransferInfo.getGoodsTransferNumber();
        Date transferTime = wGoodsTransferInfo.getGoodsTransferTime();
        String transferUserName = wGoodsTransferInfo.getCreateBy();
        Date auditTime = DateUtils.getNowDate();
        String auditUserName = getNickName();
        Double goodsTransferWeight = 0.0;

        if (StringUtils.isNull(wGoodsTransferInfo)) {
            return error("货转作业不能为空！");
        }

        if(wGoodsTransferInfo.getOriginTransferStatus().equals(wGoodsTransferInfo.getGoodsTransferStatus())){
            return new AjaxResult(500, "相同操作不能重复执行！");
        }

        // 先判断当前作业在数据库中的状态，防止2人重复操作)
        WGoodsTransferInfo goodsTransferInfo = wGoodsTransferInfoService.selectWGoodsTransferInfoByGoodsTransferId(wGoodsTransferInfo.getGoodsTransferId());
        if(StringUtils.isNull(goodsTransferInfo)) {
            return error("当前作业，已删除，作业审核失败！");
        } else if(goodsTransferInfo.getGoodsTransferStatus().equals(wGoodsTransferInfo.getGoodsTransferStatus())) {
            //logger.debug("CCC " + "audit = " + wGoodsTransferInfo);
            //logger.debug("CCC " + "audit = " + goodsTransferInfo);
            return success();
        }
        if(wGoodsTransferInfo.getGoodsTransferStatus().equals(GoodsTransferStatus.PASS.getCode())) {
            boolean checkRightOk = true;
            StringBuilder sb = new StringBuilder();
            String originGoodsRightCustomer = wGoodsTransferInfo.getOriginGoodsRightCustomer();
            String newGoodsRightCustomer = wGoodsTransferInfo.getNewGoodsRightCustomer();
//            logger.debug("BBB " + "wGoodsTransferInfo = " + wGoodsTransferInfo);

            List<TGoodsInfo> list = tGoodsInfoService.selectTGoodsInfoByTransferId(wGoodsTransferInfo.getGoodsTransferId());

            // 判断是否有货，如果无货，返回错误；注意，用isNull判断，逻辑不对，要用list个数判断
            if(list.isEmpty()) {
                return error("当前作业，无货物，作业审核失败！");
            }
            sb.append("部分货物{");

            for (TGoodsInfo item : list) {
                if (item.getGoodsRightCustomer() == null || item.getGoodsRightCustomer().isEmpty()) {
                    checkRightOk = false;
                    sb.append(item.getBundleNumber());
                    sb.append(", ");
                } else {
                    if (!item.getGoodsRightCustomer().equals(originGoodsRightCustomer)) {
                        checkRightOk = false;
                        sb.append(item.getBundleNumber());
                        sb.append(", ");
                    }
                }

                item.setOriginGoodsRightCustomer(originGoodsRightCustomer);
                item.setGoodsRightCustomer(newGoodsRightCustomer);
                item.setGoodsTransferTimes(item.getGoodsTransferTimes()+1);
//                logger.debug("BBB " + "item.getGoodsTransferIds() = " + item.getGoodsTransferIds());
                if(item.getGoodsTransferIds() == null || item.getGoodsTransferIds().isEmpty()) {
                    item.setGoodsTransferIds(wGoodsTransferInfo.getGoodsTransferId().toString() + ",");
                } else {
                    item.setGoodsTransferIds(item.getGoodsTransferIds() + wGoodsTransferInfo.getGoodsTransferId().toString() + ",");
                }
                item.setGoodsTransferNumber(transferOrderNumber);
                item.setGoodsTransferPerson(transferUserName);
                item.setGoodsTransferTime(transferTime);
                item.setGoodsTransferAuditPerson(auditUserName);
                item.setGoodsTransferAuditTime(auditTime);
                goodsTransferWeight = goodsTransferWeight + item.getWeight();
                item.setInventoryStatus("已在库");
                item.setGoodsRemark(wGoodsTransferInfo.getRemark());
            }
            sb.append("}货权方不是");
            sb.append(originGoodsRightCustomer);
            if (!checkRightOk)
                return new AjaxResult(500, sb.toString());

            rtn = tGoodsInfoService.batchUpdateTGoodsTransferRelFields(list);
//            logger.debug("CCC " + "rtn = " + rtn);
            // 货转重量，保留3位小数
            goodsTransferWeight = Math.round(goodsTransferWeight * 1000.0) / 1000.0;
            wGoodsTransferInfo.setWeight(goodsTransferWeight);

            // 货转账单
            rtn = handleGoodsTransferAccount(wGoodsTransferInfo, list);
//            logger.debug("CCC " + "handleGoodsTransferAccount rtn = " + rtn);
        } else if(wGoodsTransferInfo.getOriginTransferStatus().equals(GoodsTransferStatus.PASS.getCode())){
            boolean checkExitOk = true;
            StringBuilder sb = new StringBuilder();

            List<TGoodsInfo> list = tGoodsInfoService.selectTGoodsInfoByTransferId(wGoodsTransferInfo.getGoodsTransferId());
            String originGoodsRightCustomer = wGoodsTransferInfo.getOriginGoodsRightCustomer();
            sb.append("部分货物{");

            for (TGoodsInfo item : list) {
                if(item.getInventoryStatus().equals("已出库") ||item.getInventoryStatus().equals("出库中")) {
                    checkExitOk = false;
                    sb.append(item.getBundleNumber());
                    sb.append(", ");
                }
                item.setInventoryStatus("货转中");
                item.setGoodsRightCustomer(originGoodsRightCustomer);
                // 增加程序鲁棒性，判断货物货转ID是否为空
                if(StringUtils.isNotNull(item.getGoodsTransferIds())) {
                    item.setGoodsTransferIds(item.getGoodsTransferIds().replace(wGoodsTransferInfo.getGoodsTransferId().toString() + ",", ""));
                }
                // 增加程序鲁棒性，判断货物货转次数是否大于0，大于扣减
                if(item.getGoodsTransferTimes() > 0) {
                    item.setGoodsTransferTimes(item.getGoodsTransferTimes() - 1);
                }
                item.setGoodsTransferPerson(transferUserName);
                item.setGoodsTransferTime(transferTime);
                item.setGoodsTransferAuditPerson(auditUserName);
                item.setGoodsTransferAuditTime(auditTime);
            }
            sb.append("}出库中或已出库，不允许退回");
            if(!checkExitOk)
                return new AjaxResult(500, sb.toString());

            rtn = wGoodsTransferAccountService.deleteWGoodsTransferAccountByGoodsTransferAccountNumber(wGoodsTransferInfo.getGoodsTransferNumber().replace("TO","TA"));
            rtn = tGoodsInfoService.batchUpdateTGoodsTransferRelFields(list);
        }
//        logger.debug("CCC " + "rtn = " + rtn);

        wGoodsTransferInfo.setGoodsTransferAuditPerson(getNickName());
        wGoodsTransferInfo.setGoodsTransferAuditTime(DateUtils.getNowDate());
        wGoodsTransferInfo.setUpdateBy(getNickName());
        return toAjax(wGoodsTransferInfoService.updateWGoodsTransferInfo(wGoodsTransferInfo));
    }

    private Integer handleGoodsTransferAudit(WGoodsTransferInfo wGoodsTransferInfo)
    {
        return 0;
    }

    private Integer handleGoodsTransferAccount(WGoodsTransferInfo wGoodsTransferInfo, List<TGoodsInfo> list)
    {
        Double goodsTransferChargeWeight = 0.0;
        Integer rtn = 0;

        WGoodsTransferAccount goodsTransferAccount = new WGoodsTransferAccount();
        goodsTransferAccount.setGoodsTransferAccountNumber(wGoodsTransferInfo.getGoodsTransferNumber().replace("TO","TA"));
        goodsTransferAccount.setGoodsTransferId(wGoodsTransferInfo.getGoodsTransferId());
        goodsTransferAccount.setGoodsTransferNumber(wGoodsTransferInfo.getGoodsTransferNumber());
        goodsTransferAccount.setOriginGoodsRightCustomer(wGoodsTransferInfo.getOriginGoodsRightCustomer());
        goodsTransferAccount.setNewGoodsRightCustomer(wGoodsTransferInfo.getNewGoodsRightCustomer());

        goodsTransferAccount.setGoodsTransferStatus(wGoodsTransferInfo.getGoodsTransferStatus());
        goodsTransferAccount.setGoodsTransferTime(wGoodsTransferInfo.getGoodsTransferTime());
        goodsTransferAccount.setGoodsTransferPerson(wGoodsTransferInfo.getCreateBy());
        goodsTransferAccount.setGoodsTransferWeight(wGoodsTransferInfo.getWeight());
        //goodsTransferAccount.setNumberOfPiece(list.size());
        goodsTransferAccount.setGoodsTransferPicture(wGoodsTransferInfo.getGoodsTransferPicture());
        goodsTransferAccount.setGoodsTransferSettlementCustomer(wGoodsTransferInfo.getGoodsTransferSettlementCustomer());
        goodsTransferAccount.setGoodsTransferSettlementMode(wGoodsTransferInfo.getGoodsTransferSettlementMode());

        //原货主付货转费
        List<WGoodsTransferFeeRule> goodsTransferFeeList = wGoodsTransferFeeRuleService.selectWGoodsTransferFeeRuleByCustomerName(goodsTransferAccount.getGoodsTransferSettlementCustomer());
//        logger.debug("DDD " + "goodsTransferFeeList = " + goodsTransferFeeList);
        Double goodsTransferPrice = 0.0;
        Integer goodsTransferFreeTimes = 0, numberOfPieces = 0;
        if(goodsTransferFeeList.size() > 0) {
            for (WGoodsTransferFeeRule item : goodsTransferFeeList) {
                if (item.getRuleType().equals(RuleType.COMMON.getInfo())) {
                    goodsTransferPrice = item.getGoodsTransferPrice();
                    goodsTransferFreeTimes = item.getGoodsTransferFreeTimes();
                }
                if (item.getRuleType().equals(RuleType.CUSTOMIZED.getInfo())) {
                    goodsTransferPrice = item.getGoodsTransferPrice();
                    goodsTransferFreeTimes = item.getGoodsTransferFreeTimes();
                }
            }

            for (TGoodsInfo item : list) {
                if (item.getGoodsTransferTimes() > goodsTransferFreeTimes) {
                    goodsTransferChargeWeight = goodsTransferChargeWeight + item.getWeight();
                }
                numberOfPieces = numberOfPieces + item.getNumberOfPiece();
            }
            goodsTransferAccount.setGoodsTransferPiece(numberOfPieces);
            goodsTransferAccount.setGoodsTransferFreeTimes(goodsTransferFreeTimes);
            goodsTransferAccount.setGoodsTransferPrice(goodsTransferPrice);
            goodsTransferAccount.setGoodsTransferChargeWeight(goodsTransferChargeWeight);
            goodsTransferAccount.setGoodsTransferDiscountAmount(0.0);
            //DecimalFormat df3 = new DecimalFormat("#.000");
            goodsTransferAccount.setGoodsTransferChargeWeight(Math.round(goodsTransferChargeWeight * 1000.0) / 1000.0);
            //DecimalFormat df2 = new DecimalFormat("#.00");
            goodsTransferAccount.setGoodsTransferFee(Math.round(goodsTransferPrice * goodsTransferChargeWeight * 100.0) / 100.0);
            goodsTransferAccount.setCreateBy(getNickName());

//            logger.debug("FFF " + "goodsTransferAccount = " + goodsTransferAccount);

            rtn = wGoodsTransferAccountService.deleteWGoodsTransferAccountByGoodsTransferAccountNumber(goodsTransferAccount.getGoodsTransferAccountNumber());
//            logger.debug("GGG " + "rtn = " + rtn);
            rtn = wGoodsTransferAccountService.insertWGoodsTransferAccount(goodsTransferAccount);
//            logger.debug("HHH " + "rtn = " + rtn);
        } else {
            logger.debug("EEE " + "goodsTransferFeeList.size() = " + goodsTransferFeeList.size());
//            return 0;
        }

        return rtn;

    }
    /**
     * 货转时间线信息
     */
    @PreAuthorize("@ss.hasPermi('transfers:trace:track')")
//    @Log(title = "货转信息", businessType = BusinessType.DELETE)
    @GetMapping("/trace/{goodsTransferIds}")
    public AjaxResult trace(@PathVariable String goodsTransferIds)
//    public AjaxResult trace(@PathVariable Long[] goodsTransferIds)
    {
        List<TimeLineActivity> list = wGoodsTransferInfoService.selectTimeLineActivityByGoodsTransferId(goodsTransferIds);
//        logger.debug("FFF " + "rtn = " + list);
        return success(list);
    }

    /**
     * 获取货物重量合计
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:query')")
    @GetMapping(value = "/transferweightsum")
    public AjaxResult transferWeightSum(WGoodsTransferInfo wGoodsTransferInfo)
    {
        List<TGoodsWeightSum> list = wGoodsTransferInfoService.getWeightSumByGoodsTransferInfo(wGoodsTransferInfo);
//        logger.debug("GGG " + "getWeightSumByGoodsTransferInfo = " + list);
        return success(list);
    }

}
